#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from typing import Optional, List

from core.crud import CRUDBase
from app.admin.model.user import User
from app.admin.schema.user import UserCreate, UserUpdate
from common.exception.errors import CustomException
from common.response.response_code import HttpCode
from common.log import log
from utils.password_util import PasswordUtil

class UserService(CRUDBase[User, UserCreate, UserUpdate]):
    
    @classmethod
    def get_model(cls) -> User:
        return User
    
    @classmethod
    async def get_by_name(cls, username: str) -> Optional[User]:
        return await cls.get_model().filter(username=username).first()
    
    @classmethod
    async def delete_by_ids(cls, ids: List[int]) -> bool:
        await cls.get_model().filter(id__in=ids).all().delete()
        return True
    
    @classmethod
    async def bulk_delete(self, users: List[User]) -> bool:
        delete_ids = [user.id for user in users]
        await self.delete_by_ids(delete_ids)
        return True
    
    @classmethod
    async def delete_by_name(cls, username: str) -> bool:
        user = await cls.get_by_name(username)
        if not user:
            raise CustomException(
                code=HttpCode.HTTP_404,
                msg="用户不存在"
            )
        await cls.remove(user.id)
        return True
    
    @classmethod
    async def authenticate(
        cls, 
        username: str, 
        password: str
    ) -> Optional[User]:
        db_user = await cls.get_by_name(username)
        if not db_user:
            return None
        if not PasswordUtil.verify_password(password, db_user.password):
            return None
        return db_user
    
    @classmethod
    async def create_user(
        cls,
        obj_in: User | UserCreate
    ) -> User:
        obj_in.password = PasswordUtil.get_password_hash(obj_in.password)
        return await cls.create(obj_in)